<?php
namespace App\Admin;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Config;
use Illuminate\Http\Request;

use App\Admin\Models\User as AdminUserModel;

class AdminServiceProvider extends ServiceProvider
{

    private static $adminGuardName = 'admin-token';

    /**
     * 启动服务
     */
    public function boot(): void
    {
        if (!config('admin.enabled')) {
            return;
        }

        // 注册看守器
        $this->registerGuard();
        Auth::viaRequest(static::$adminGuardName, [$this, 'guard']);

        // 注册路由
        $this->registerRoutes();
    }

    public function registerGuard()
    {
        Config::set('auth.guards.admin', [
            'driver' => static::$adminGuardName,
            'provider' => 'admin',
        ]);
        Config::set('auth.providers.admin', [
            'driver' => 'eloquent',
            'model' => App\Admin\Models\User::class,
        ]);
    }

    /**
     * 注册后台路由
     */
    protected function registerRoutes()
    {
        Route::middlewareGroup('admin.api', config('admin.middleware', []));
        Route::group([
            'domain' => config('admin.domain', null),
            'namespace' => 'App\Admin\Controllers',
            'prefix' => config('admin.path', 'admin-api'),
            'middleware' => 'admin.api',
        ], function () {
            // $this->loadRoutesFrom(__DIR__.'/routes.php');
            $this->loadRoutesFrom(base_path('routes/admin.php'));
        });
    }


    /**
     * 注册后台看守器
     */
    public function guard(Request $request)
    {
        $token = Admin::getAuthorization($request);

        if( empty($token) ){
            return null;
        }

        $uid = Redis::get($token);
        if( $uid==null ){
            return null;
        }

        return AdminUserModel::where('id', $uid)->first();
    }
}
